package io.kimmking.gateway.config;

import com.alibaba.cloud.nacos.parser.NacosDataYamlParser;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * 获取配置中心Nacos里的配置组信息
 */
@Configuration
@Slf4j
public class NacosConfig {
    @Value("${spring.cloud.nacos.discovery.server-addr}")
    public String NACOS_SERVER_ADDR;

    @Value("${spring.cloud.nacos.config.namespace}")
    public String NACOS_NAMESPACE;

    @Value("${nacos.gateway.route.config.data-id}")
    public String NACOS_ROUTE_DATA_ID;

    @Value("${nacos.gateway.route.config.group}")
    public String NACOS_ROUTE_GROUP;

    public static final long DEFAULT_TIMEOUT=3000l;

    /**
     * 初始化网关路由 nacos config
     * @return
     */
    @Bean
    public ConfigService configService() {
        try {
            Properties properties = new Properties();
            properties.setProperty("serverAddr", NACOS_SERVER_ADDR);
            properties.setProperty("namespace", NACOS_NAMESPACE);
            return NacosFactory.createConfigService(properties);
        } catch (Exception e) {
            log.error("初始化网关路由时发生错误", e);
            return null;
        }
    }

    @Bean
    public NacosDataYamlParser nacosDataYamlParser(){
        return new NacosDataYamlParser();
    }
}
